package com.flame.shapeville.controller;

import com.flame.shapeville.bean.User;
import com.flame.shapeville.enums.SceneStyle;
import com.flame.shapeville.factory.BeanFactory;
import com.flame.shapeville.service.TaskService;
import com.flame.shapeville.service.UserService;
import com.flame.shapeville.util.Utils;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

/**
 * Controller responsible for handling user login functionality.
 * <p>
 * This class provides methods to authenticate and create users,
 * and initializes the login view with existing user data if available.
 *
 * @author Flame Dev Team
 * @version 1.0
 * @since 2025-05-08
 */
public class LoginController implements JfController {

    /**
     * Input field for entering the username.
     */
    @FXML
    private TextField username;

    /**
     * The currently logged-in user.
     */
    private User user;

    /**
     * Service for user-related operations.
     */
    private UserService userService;

    /**
     * Service for task-related operations.
     */
    private TaskService taskService;

    /**
     * Handles login button click event.
     * Authenticates or creates a new user and navigates to the course scene.
     */
    @FXML
    private void login() {
        String name = username.getText().trim();
        boolean checked = userService.checkUser(name);
        if (!checked) {
            userService.createUser(name);
        }
        user = (User) BeanFactory.getBean("user");
        userService.flushLatestLogin();
        SceneController.setSceneStyle(SceneStyle.COURSE);
    }

    /**
     * Handles Enter key press in the username field to trigger login.
     *
     * @param event the key event
     */
    @FXML
    private void enterLogin(KeyEvent event) {
        if (event.getCode() == KeyCode.ENTER && username.isFocused())
            login();
    }

    /**
     * Initializes the controller with user data and sets up input behavior.
     */
    @Override
    public void init() {
        userService = (UserService) BeanFactory.getBean("userService");
        taskService = (TaskService) BeanFactory.getBean("taskService");
        user = userService.getUser();
        if (user != null) {
            BeanFactory.setBean("user", user);
            Platform.runLater(() -> {
                username.setText(user.getName());
                username.positionCaret(username.getText().length());
                username.deselect();
            });
        } else {
            username.setFocusTraversable(false);
        }
        Utils.addClickOutsideToLoseFocus(username, event -> username.getParent().requestFocus());
    }
}
